import { getDiff } from '@/utils/tools';
import dayjs, { Dayjs } from 'dayjs';
import log from '@/utils/log';
import { getContent, sendMsg } from '../dingtalk/func';
import { pmUserList, qaUserList } from '../configs/tapd';

/**
 * 获取需求状态的排序状态
 * @param status
 */
function getNormalStatusSort(status) {
  switch (status) {
    // 需求发起
    case 'planning':
      return 0;
    // PRD撰写中
    case 'resolved':
      return 1;
    // PRD完成（待评审、UI设计中）
    case 'status_13':
      return 2;
    // 排期中（PRD评审通过）
    case 'status_3':
      return 3;
    // 排期完成（待进入开发）
    case 'status_17':
      return 4;
    // 开发中
    case 'status_4':
      return 5;
    // 提交测试（UI走查）
    case 'status_10':
      return 6;
    // 测试完成（待灰度UI走查完成）
    case 'status_11':
      return 7;
    // 灰度验证完成
    case 'status_9':
      return 8;
    // 生产发布完成
    case 'status_5':
      return 9;
    // 项目目标review
    case 'status_7':
      return 10;
    // 归档
    case 'status_8':
      return 11;
    // 需求评审未通过
    case 'status_2':
      return 80;
    // 需求暂停
    case 'status_6':
      return 81;
    // 需求关闭
    case 'status_28':
      return 82;
    // 已拒绝
    case 'rejected':
      return 83;
    default:
      return 100;
  }
}

/**
 * 普通需求开发流程
 * @param event 事件信息
 * @param currentDate 当前时间
 * @param res 响应对象
 * @returns
 */
async function developFlow(event: TapdStoryEventType, currentDate: Dayjs) {
  const {
    id,
    name,
    custom_field_two: cftwo,
    custom_field_six: techOwner,
    custom_field_eight: cfeight,
    custom_field_10: cf10,
    custom_field_11: cf11,
    custom_field_12: cf12,
    custom_field_14: cf14,
    owner,
    status,
  }: TapdStoryEventType = event;

  const devStartDate = dayjs(cf11);
  const jointDebuggingDate = dayjs(cf12);
  const testStartDate = dayjs(cftwo);
  const checkDate = dayjs(cf14);
  const deployDate = dayjs(cf10);
  const reviewDate = dayjs(cfeight);

  const statusNum = getNormalStatusSort(status);
  let differ: number = getDiff(currentDate, reviewDate);
  // 需求目标review日期通知项管
  if (differ >= 0) {
    await sendMsg(id, pmUserList, name, '该需求已到达需求目标review时间，请及时收集review结果！');
  }
  differ = getDiff(currentDate, deployDate);
  // 发布阶段通知测试同学
  if (differ >= 0 && statusNum < 9) {
    let list = qaUserList;
    // 超过2天，通知项管
    if (differ >= 2) {
      list = list.concat(pmUserList);
    }
    const content = getContent(`该需求${differ === 0 ? '今日计划进入发布阶段' : `已进入发布阶段第${differ}天`}，请及时更新需求状态/同步风险。`, owner, techOwner);
    await sendMsg(id, list, name, content);
    return;
  }
  differ = getDiff(currentDate, checkDate);
  // 到达验收节点，提醒
  if (differ >= 0 && statusNum < 7) {
    let list = qaUserList;
    // 超过2天，通知项管
    if (differ >= 2) {
      list = list.concat(pmUserList);
    }
    const content = getContent(`该需求${differ === 0 ? '今日计划进入验收阶段' : `已进入验收阶段第${differ + 1}天`}，请及时更新需求状态/同步风险。`, owner, techOwner);
    await sendMsg(id, list, name, content);
    return;
  }
  differ = getDiff(currentDate, testStartDate);
  // 到达提测节点，状态还未到提交测试
  if (differ >= 0 && statusNum < 6) {
    let list = techOwner.concat(owner);
    // 超过2天，通知项管
    if (differ >= 2) {
      list = list.concat(pmUserList);
    }
    const content = getContent(`该需求${differ === 0 ? '今日计划进入测试阶段' : `已进入测试阶段第${differ + 1}天`}，请及时更新需求状态/同步风险。`, owner, techOwner);
    await sendMsg(id, list, name, content);
    return;
  }
  differ = getDiff(currentDate, jointDebuggingDate);
  // 到达联调节点，提醒owner
  if (differ === 0) {
    const list = techOwner;
    const content = getContent('该需求今日计划进入联调阶段。', owner, techOwner);
    await sendMsg(id, list, name, content);
    return;
  }
  differ = getDiff(currentDate, devStartDate);
  // 到达开发时间节点，状态还未到开发中
  if (differ >= 0 && statusNum < 5) {
    let list = techOwner.concat(owner);
    // 超过2天，通知项管
    if (differ >= 2) {
      list = list.concat(pmUserList);
    }
    const content = getContent(`该需求${differ === 0 ? '今日计划进入开发阶段' : `已进入开发阶段第${differ + 1}天`}，请及时更新需求状态/同步风险。`, owner, techOwner);
    await sendMsg(id, list, name, content);
  }
}
/**
 * 里程碑功能实现
 * @param event 事件对象
 */
const milestoneHandler = async (event: TapdStoryEventType) => {
  const { id, name, object_type: objectType, custom_field_22: cf22, custom_field_six: techOwner, workitem_type_id: workItemTypeId, owner, creator, due, status, created }: TapdStoryEventType = event;
  // 判断是需求
  if (objectType !== 'story') {
    log.error('/api/tapd/milestone只处理需求', JSON.stringify(event));
    throw Error('这里只处理需求');
  }
  const currentDate = dayjs(cf22);
  /**
   * 一般业务需求类型
   */
  const isNormalStory = workItemTypeId === '1141194427001000003';
  /**
   * 技术需求
   */
  const isTechStory = workItemTypeId === '1141194427001000009';
  /**
   * 紧急需求
   */
  const isEmergencyStory = workItemTypeId === '1141194427001000016';
  /**
   * 数据需求
   */
  const isDataStory = workItemTypeId === '1141194427001000007';
  /**
   * 工单
   */
  const isWorkOrderStory = workItemTypeId === '1141194427001000019';
  /**
   * 临时取数需求
   */
  const isTempDataStory = workItemTypeId === '1141194427001000017';

  if (isNormalStory || isTechStory || isEmergencyStory) {
    await developFlow(event, currentDate);
  }
  let differ = getDiff(currentDate, dayjs(created), 'month');
  // 需求创建时间超三个月，始终是需求发起状态，通知创建人及项管
  if (differ >= 3 && status === 'planning') {
    const users = Array.isArray(creator) ? creator : [creator];
    await sendMsg(id, users.concat(pmUserList), name, '该需求创建已超三月且无跟进信息，请及时确认是否关闭需求！');
  }
  differ = getDiff(currentDate, dayjs(due));
  if (differ >= 0) {
    let list = owner.concat(techOwner);
    if (differ >= 2) {
      list = list.concat(pmUserList);
    }
    // 产品数据需求到达预计结束时间，状态不是【生产发布完成、已取消、已拒绝】，提醒处理人调整状态
    if (isDataStory && status !== 'status_5' && status !== 'status_26' && status !== 'rejected') {
      const content = getContent('该需求已到达预计结束时间，请及时调整状态！', owner, techOwner);
      await sendMsg(id, list, name, content);
    } else if (isWorkOrderStory && status !== 'status_21' && status !== 'rejected') {
      const content = getContent('工单已到达预计结束时间，请及时调整状态！', owner, techOwner);
      // 工单需求到达预计结束时间，状态不是【已实现、已拒绝】，提醒处理人调整状态
      await sendMsg(id, list, name, content);
    } else if (isTempDataStory && status !== 'status_25' && status !== 'rejected') {
      const content = getContent('该需求已到达预计结束时间，请及时调整状态！', owner, techOwner);
      // 临时取数需求到达预计结束时间，状态不是【数据开发完成、已拒绝】，提醒处理人调整状态
      await sendMsg(id, list, name, content);
    }
  }
};

export default milestoneHandler;
